/*
 *   This file is part of verbum.
 *
 *   poat is free software: you can redistribute it and/or modify
 *   it under the terms of the GNU General Public License as published by
 *   the Free Software Foundation, either version 3 of the License, or
 *   (at your option) any later version.
 *
 *   poat is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *   GNU General Public License for more details.
 *
 *   You should have received a copy of the GNU General Public License
 *   along with poat.  If not, see <http://www.gnu.org/licenses/>.
 * 
 * 	 Copyright (c) 2008 Sergio Gabriel Teves <gabriel.sgt at gmail.com>
 */

var lastSvnUser = "";

function upRender(value, p, record) {
	var str = String.format(_('File uploaded by {0} on {1}'),record.data.userid,renderUserDate(record.data.udate));
	return "<span class=\"uploaded-files-header\">"+str+"</span>";
}

function renderUploadStatus(value, p, record) {
	var str="";
	switch (value) {
		case "4":
			str = _('Failed');
			break;
		case "3":
			str = _('Processing');
			break;
		case "2":
			str = _('Submitted');
			break;
		default:
			if (record.data.takeuser!="") {
				str = _('Locked');
			} else {
				str = _('Pending');
			}			
	}
	return str;
}

function onUploadListContextMenu(grid, rowIndex, e) {
    e.stopEvent();
    grid.selModel.selectRow(rowIndex);

    var listContextMenu = new Ext.menu.Menu({
    	items: [
    		{
    			iconCls: 'download',
    			text: _('Download'),
    			handler: function() {
    				var selections = grid.selModel.getSelections();
    				fetchFile(selections[0].json.id,"up");
    			}
    		}
    	]
    });
    
    listContextMenu.showAt(e.getXY());
}

function submitFiles(ed,cmd) {
	var selections = ed.selModel.getSelections();
	if (ed.selModel.getCount()>0) {

		var util = new Verbum.Utilities();
		
		if (cmd=="nok") {
			util.ask({
				title: _('Add comment'),
				msg: _('Enter a comment'),
				allowBlank: false,
			})
		} else {
			util.ask({
				title: _('Add comment'),
				msg: _('Enter a comment (optional)')
			})
		}		

		util.on({
			'press_ok': function(text) {
			  	var encoded_array = "";
			  	for(i = 0; i< ed.selModel.getCount(); i++){
			  		if (i>0) {
			  			encoded_array = encoded_array + ":";
			  		}
					encoded_array = encoded_array + selections[i].json.id;
			  	}
			  								        
				lMask = new Ext.LoadMask(ed.getEl(), {msg: _('Please wait...'), removeMask: true});
				lMask.show();
														
				Ext.Ajax.request({ 
			           url: getMainUrl(), 
			           params: { 
			              action: "upload_manager",
			              id: encoded_array,
			              op: cmd,
			              comment: text
			             }, 
			           success: function(response){
			           	obj = Ext.util.JSON.decode(response.responseText);
			           	if (obj.success==false) {
			           		Ext.Msg.error(obj.error);
			           	} else {
							ed.store.load();
			           	}
			           },
					callback: function ( options, success, response ) { 
						lMask.hide();
					}														            
			   	});	
		}});

	
	} else {
		Ext.Msg.message(_('Please, select an item from the list.'));
	}
}

function submitFilesSVN(ed,desktop) {

	if (ed.selModel.getCount()==0) {
		Ext.Msg.message(_('Please, select an item from the list.'));
	} else {
		var bbar = new Ext.Toolbar({
			items:['->',
				{
					xtype:'button',
					tooltip: _('Cancel'),
					iconCls: 'cancel',
					text: _('Cancel'),
					handler: function() {
						win.close();
					}
				},
				{
					xtype:'button',
					tooltip: _('Ok'),
					iconCls: 'ok',
					text: _('Ok'),
					handler: function() {
						pForm = form;
						if (pForm.getForm().isValid()) {
							lastSvnUser	= pForm.findById('userid').getValue();
							
							var selections = ed.selModel.getSelections();
							if (ed.selModel.getCount()>0) {

								var util = new Verbum.Utilities();
								util.ask({
									title: _('Add comment'),
									msg: _('Enter a comment (optional)')
								})

								util.on({
									'press_ok': function(text) {
										var encoded_array = "";
									  	for(i = 0; i< ed.selModel.getCount(); i++){
									  		if (i>0) {
									  			encoded_array = encoded_array + ":";
									  		}
											encoded_array = encoded_array + selections[i].json.id;
									  	}
									  	
										util.request({
											el: ed.getEl(),
								            params: { 
								               action: "upload_manager", 
								               id: encoded_array,
								               op: 'svn',
								               uid: pForm.findById('userid').getValue(),
								               psd: pForm.findById('password').getValue(),
								               comment: text
								              }											
										});										
									},
									'done': function(response) {
										obj = Ext.util.JSON.decode(response.responseText);
										/*if (obj.ret) {
											Ext.Msg.message(obj.ret);	
										}*/
										ed.store.reload();
									}
								});				

								win.close();

							} else {
								Ext.Msg.message(_('Please, select an item from the list.'));
							}
						}
					}
				}]		
		});
		
	    var form = new Ext.form.FormPanel({
	        baseCls: 'x-plain',
	        url:getMainUrl(),
	        defaultType: 'textfield',
	        buttonAlign:'right',
	        waitMsgTarget: true,
	        bbar: bbar,
	        autoWidth: true,
	        autoHeight: true,
	        defaults: {msgTarget:'side', allowBlank: false, width: 200},
	        monitorResize: true,
	        items: [
			{
	        	xtype: 'label',
	        	html: _("Enter your SVN credential to commit the files. It won't be saved.")
	        },{
	            fieldLabel: _('Username'),
	            name: 'userid',
	            id: 'userid',
	            blankText: _('Please, enter a valid Username.'),
	            value: lastSvnUser || ""
	        },{
	            fieldLabel: _('Password'),
	            name: 'password',
	            id: 'password',
	            inputType: 'password',
	            blankText: _('Please, enter a valid Password.')
	        }]
	    });
	
	    var win = desktop.createWindow({
	        title: _('Submit the selected files to SVN'),
	        width: 350,
	        minWidth: 350,
	        minHeight: 250,
	        layout: 'fit',
	        bodyStyle:'padding:5px;',
	        items: form,
			resizable: false,
			closable: false,
			draggable: true,
			maximizable: false,
			minimizable: false,
			iconCls: 'svn-submit'
	    });
	
	    win.show();
	    
	    win.on({
	    	'show': function() {
	    		focus(form,'userid');	
	    	}
	    })
			
	}

/*
	var selections = ed.selModel.getSelections();
	if (ed.selModel.getCount()>0) {
	  	var encoded_array = "";
	  	for(i = 0; i< ed.selModel.getCount(); i++){
	  		if (i>0) {
	  			encoded_array = encoded_array + ":";
	  		}
			encoded_array = encoded_array + selections[i].json.id;
	  	}
	  								        
		lMask = new Ext.LoadMask(ed.getEl(), {msg: _('Please wait...'), removeMask: true});
		lMask.show();
												
		Ext.Ajax.request({ 
	           url: getMainUrl(), 
	           params: { 
	              action: "upload_manager",
	              id: encoded_array,
	              op: cmd
	             }, 
	           success: function(response){
	           	obj = Ext.util.JSON.decode(response.responseText);
	           	if (obj.success==false) {
	           		Ext.Msg.error(obj.error);
	           	} else {
					ed.store.load();
	           	}
	           },
			callback: function ( options, success, response ) { 
				lMask.hide();
			},														            
	   	});	
	
	} else {
		Ext.Msg.message(_('Please, select an item from the list.'));
	}*/
}

MyDesktop.UploadListModule = Ext.extend(Ext.app.Module, {
	id:'uploadlist-win',
	text: _('Upload Manager'),
    init : function(){
        this.launcher = {
            text: this.text,
            iconCls: 'upload-list',
            handler : this.createWindow,
            windowId : 'upList',
            scope: this
        }
    },
    
    createWindow : function(src){

        var desktop = this.app.getDesktop();
        var winname = 'uploadlist-win';
        var win = desktop.getWindow(winname);
		
        if(!win){
        	var uploadListEd;
			 					
			var uploadListTB = new Ext.Toolbar({
			            items:[{
			                text: _('Lock/Unlock'),
			                tooltip: _('Lock the selected files avoiding other users to submit them by mistake'),
			                cls: 'x-btn-text-icon take-button',
			                handler: function(btn, pressed) {
			                		var selections = uploadListEd.selModel.getSelections();
							        if (uploadListEd.selModel.getCount()>0) {
									  	
									  	var encoded_array = "";
									  	for(i = 0; i< uploadListEd.selModel.getCount(); i++){
									  		if (i>0) {
									  			encoded_array = encoded_array + ":";
									  		}
											encoded_array = encoded_array + selections[i].json.id;
									  	}
									  								        
										lMask = new Ext.LoadMask(uploadListEd.getEl(), {msg: _('Please wait...'), removeMask: true});
    									lMask.show();
    																
										Ext.Ajax.request({ 
								            url: getMainUrl(), 
								            params: { 
								               action: "upload_manager",
								               id: encoded_array,
								               op: "toggle"
								              }, 
								            success: function(response){
								            	obj = Ext.util.JSON.decode(response.responseText);
								            	if (obj.success==false) {
								            		Ext.Msg.error(obj.error);
								            	} else {
													uploadListEd.store.load();
								            	}
								            },
											callback: function ( options, success, response ) { 
												lMask.hide();
											},														            
									   	});	

									} else {
										Ext.Msg.message(_('Please, select an item from the list.'));
									}
			                	}
	    					},"-", {
			                text: _('Accept'),
			                cls: 'x-btn-text-icon submit-button',
			                tooltip: _('Accept the selected files submitted manually'),
			                handler: function(btn, pressed) {
			                		submitFiles(uploadListEd,"ok");
			                	}
							}, {
			                text: _('Reject'),
			                cls: 'x-btn-text-icon reject-button',
			                tooltip: _('Reject the selected files'),
			                handler: function(btn, pressed) {
			                		submitFiles(uploadListEd,"nok");
			                	}
							},{
			                text: _('Commit'),
			                cls: 'x-btn-text-icon svn-submit-button',
			                tooltip: _('Commit the selected files automatically'),
			                handler: function() {
									submitFilesSVN(uploadListEd,desktop);									
			                	}
							},'-',
			                {
							xtype: 'combo',
							editable: false,
							triggerAction: 'all',
						   	store: [['false',_('No taken')],['true',_('All')]],
						   	width: 100,
						   	value: 'false',
						   	listeners: {select: 
						   				function(combo,record,index) {
						   					uploadListEd.store.load({params:{all:record.data.value}});
						   				}
						   		}
			                },'-',
							{
								xtype:'button',
								tooltip: _('Refresh'),
								iconCls: "x-tbar-loading",
								handler: function() {
									uploadListEd.store.reload();	
								}
							}								
							]
			        });
        	
        	var uploadListSM = new Ext.grid.CheckboxSelectionModel();
			
			var uploadListEd = new Ext.grid.GridPanel({
				id: 'uploadManGrid',
		        store: new Ext.data.Store({
					reader: new Ext.data.JsonReader({
						root: 'results'
						},[
							{name: 'id'},
							{name: 'userid'},
							{name: 'udate'},
							{name: 'statusid'},
							{name: 'teamid'},
							{name: 'projectid'},
							{name: 'takeuser'},
							{name: 'takedate'},
							{name: 'data'}
					]),
					proxy: new Ext.data.HttpProxy({
						url: getMainUrl(),
						method: 'POST'
					}),
					baseParams: {action: 'upload_manager'},
		            sortInfo:{field: 'udate', direction: "DESC"}		            
		        }),
		        columns: [
		            	{
		            		header: _('Files'),
		            		dataIndex: 'udate',
		            		renderer: upRender,
		            		width: 230,
		            		sortable: true,
		            	},
		            	{
		            		header: _('Locked by'),
							dataIndex: 'takeuser',
							sortable: true,
						},
		            	{
		            		header: _('Locked on'),
							dataIndex: 'takedate',
							sortable: true,
							renderer: renderUserDate
						},
		            	{
		            		header: _('Status'),
							dataIndex: 'statusid',
							sortable: true,
							renderer: renderUploadStatus
						},						
						uploadListSM
		        ],
		        selModel: uploadListSM,
		        tbar: uploadListTB,
				view: new Ext.grid.GridView({
					forceFit:true,
            		enableRowBody:true,
            		getRowClass : function(record, rowIndex, p, store) {
            					//var cls='';
	            				var b = "<ul class=\"uploaded-files\">";
	            				for (i=0;i<record.data.data.length;i++) {
	            					b += "<li class=\"uploaded-files-item\">"+record.data.data[i].name+"</li>";
	            				}
	            				p.body = b+"</ul>";
	            				/*
	            				if (record.data.takeuser!="") {
	            					cls = 'red-row';
	            				}
									            				
	            				return cls;*/
            				}
						}),
			    collapsible: true,
    			animCollapse: false,
			});
			
            win = desktop.createWindow({
				id: winname,
				closable:true,
				width:640,
				height:480,
				plain:true,
				layout: 'fit',
				iconCls: 'upload-list',
				items: uploadListEd,
				title: this.text
            });

			uploadListEd.store.load();

			uploadListEd.on('rowcontextmenu', onUploadListContextMenu);
        }
        win.show();
    }
});